package com.cloud.upms.service.impl;

import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloud.common.core.constant.CommonConstants;
import com.cloud.common.core.exception.ProjectException;
import com.cloud.common.core.result.Result;
import com.cloud.common.satoken.core.domain.LoginUser;
import com.cloud.api.upms.model.SysUser;
import com.cloud.api.upms.model.SysUserRole;
import com.cloud.api.upms.domain.user.UserAddReq;
import com.cloud.api.upms.domain.user.UserListReq;
import com.cloud.api.upms.domain.user.UserUpdateReq;
import com.cloud.api.upms.enums.UserExceptionEnum;
import com.cloud.common.satoken.util.LoginUtil;
import com.cloud.upms.dao.SysRoleMapper;
import com.cloud.upms.dao.SysUserMapper;
import com.cloud.upms.dao.SysUserRoleMapper;
import com.cloud.upms.service.SysRoleService;
import com.cloud.upms.service.SysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


@Service
@RequiredArgsConstructor
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    private final SysUserMapper sysUserMapper;
    private final SysUserRoleMapper sysUserRoleMapper;
    private final SysRoleMapper sysRoleMapper;



    @Override
    public Result<LoginUser> getUserInfo(String userName) {
        SysUser user = this.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserName, userName));
        if (user == null) {
            return Result.error("未查到用户信息");
        }
        List<Long> roleIds=sysRoleMapper.getRoleIds(user.getId());
        //权限
        List<String> permissions=new ArrayList<>();
        //1.添加菜单和按钮权限
        if(CollUtil.isNotEmpty(roleIds)){
            permissions.addAll(sysRoleMapper.getRolePermission(roleIds));
        }
        //2.其他权限
        //todo

        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(user.getId());
        loginUser.setUsername(user.getUserName());
        loginUser.setPassword(user.getPassword());
        loginUser.setRoleCodes(sysRoleMapper.getRoleCodes(user.getId()));
        loginUser.setRoleIds(roleIds);
        loginUser.setDeptId(user.getDeptId());
        loginUser.setPermissions(permissions);

        return Result.success(loginUser);
    }

    @Override
    @Transactional
    public void add(UserAddReq param) {
        String userName=param.getUserName();
        String password=param.getPassword();
        Long count=sysUserMapper.selectCount(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUserName,userName)
                .eq(SysUser::getDelFlag, CommonConstants.ZERO)
        );
        if(count>0){
            throw new ProjectException(UserExceptionEnum.USERNAME_EXIST);
        }
        //1.保存用户
        SysUser user=new SysUser();
        user.setDeptId(param.getDeptId());
        user.setUserName(userName);
        user.setPassword(BCrypt.hashpw(password));
        user.setName(param.getName());
        user.setPhone(param.getPhone());
        user.setStatus(param.getStatus());
        this.saveOrUpdate(user);

        //2.清除老的角色
        Long userId=user.getId();
        sysUserRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getSysUserId,userId));

        //3.保存新的角色

        List<Long> roleIds=param.getRoleIds();
        if(CollUtil.isNotEmpty(roleIds)){
            roleIds.forEach(roleId->{
                SysUserRole userRole=new SysUserRole();
                userRole.setSysRoleId(roleId);
                userRole.setSysUserId(userId);
                sysUserRoleMapper.insert(userRole);
            });
        }
    }

    @Override
    @Transactional
    public void update(UserUpdateReq req) {
        Long id=req.getId();
        SysUser user=sysUserMapper.selectById(id);
        if(user==null){
            throw new ProjectException(UserExceptionEnum.USER_NOT_EXIST);
        }
        //更新用户
        user.setDeptId(req.getDeptId());
        user.setName(req.getName());
        user.setPhone(req.getPhone());
        user.setStatus(req.getStatus());
        this.saveOrUpdate(user);

        //2.清除老的角色
        sysUserRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getSysUserId,id));

        //3.保存新的角色
        List<Long> roleIds=req.getRoleIds();
        if(CollUtil.isNotEmpty(roleIds)){
            roleIds.forEach(roleId->{
                SysUserRole userRole=new SysUserRole();
                userRole.setSysRoleId(roleId);
                userRole.setSysUserId(id);
                sysUserRoleMapper.insert(userRole);
            });
        }
    }

    @Override
    public List<SysUser> listUser(UserListReq paramReq) {
        return sysUserMapper.listUser(paramReq);
    }

    @Override
    public void enable(Long id, Integer status) {
        SysUser user=sysUserMapper.selectById(id);
        if(user==null){
            throw new ProjectException(UserExceptionEnum.USER_NOT_EXIST);
        }
        if(status==null){
            throw new ProjectException(UserExceptionEnum.STATUS_NOT_BLANK);
        }
        user.setStatus(status);
        this.saveOrUpdate(user);

        String loginId=user.getLoginId();
        switch (status){
            case 0:
                //启用
                StpUtil.untieDisable(loginId);
                break;
            case 1:
                //禁用
                StpUtil.kickout(loginId);
                StpUtil.disable(user.getLoginId(),-1);
                break;
        }
    }
}
